import os
import sys
from pebble import ProcessPool, ProcessExpired
from multiprocessing import cpu_count
import subprocess
import shutil
import argparse
import re



def run_command(command):
    print(f"Running command: {command}")
    result = subprocess.run(command, shell=True)
    return result.returncode == 0

def execute_parallel_commands_multiprocess(minute):
    # 定义三个并行执行的命令
    commands = [
        f'scheduler -d {minute}m -v -n "framedump complete!"',
        f'adb shell test_cam_framedump 2 {minute}',
        f'adb shell test_cam_framedump 3 {minute}'
    ]
    
    # 使用进程池并行执行
    # with multiprocessing.Pool(processes=3) as pool:
    #     results = pool.map(run_command, commands)
    with ProcessPool(max_workers=min(len(commands), cpu_count())) as pool:
        futures = []
        try:
            # 提交所有转换任务
            for command in commands:
                future = pool.schedule(
                    run_command, 
                    args=(command,)
                )
                futures.append(future)
                for future in futures:
                    result = future.result()  
        except KeyboardInterrupt:
            print("\n用户中断请求，正在取消所有任务...")
            # 取消所有未完成的任务
            for future in futures:
                if not future.done():
                    future.cancel()
            # 等待已启动的任务完成
            pool.stop()
            pool.join(timeout=5)
            print("所有任务已终止")
            sys.exit(1)
    print("parallel commands executed.")

def main():
    minute = sys.argv[1] if len(sys.argv) > 1 else 1
    print(f"Minute: {minute}")
    run_command('adb wait-for-device')
    run_command('adb devices')
    run_command('adb root')
    run_command('adb remount')
    run_command('adb shell rm /sdcard/Pictures/*')
    run_command('adb shell "test_vxr_camera_parameter get rgb-left exposure && test_vxr_camera_parameter get rgb-left gain && test_vxr_camera_parameter get rgb-right exposure && test_vxr_camera_parameter get rgb-right gain" > exposure_gain.txt')
    run_command('adb push exposure_gain.txt /sdcard/Pictures/exposure_gain.txt')
    execute_parallel_commands_multiprocess(minute)
    # run_command(f'adb shell /data/local/tmp/yuv_rename.sh /sdcard/Pictures/')


if __name__ == "__main__":
    main()
